package com.atguigu02.tcpudp;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * ClassName: dataTransmissionTest
 * Package: com.atguigu02.tcpudp
 * Description:
 *      进行文字以及图片的传输
 * @Author BuTang
 * @Create 2023/6/20 15:44
 * @Version 1.0
 */
public class DataTransmissionTest {

    //客户端
    @Test
    public void test1() throws IOException {

        //1.创建一个socket
        int port = 8989;
        InetAddress inetAddress = InetAddress.getLocalHost();
        Socket socket = new Socket(inetAddress,port);

        //2.发送数据
        OutputStream ou = socket.getOutputStream();
        ou.write("你好，我是客户端".getBytes());


        //3.关闭流
        socket.close();
        ou.close();
    }

    //服务器端
    @Test
    public void test2() throws IOException {
        //1.创建serverSocket
        int port = 8989;
        ServerSocket serverSocket = new ServerSocket(port);

        //2.接收到客户端的IP地址
        Socket socket = serverSocket.accept();

        //3.创建属于客户端的输入流
        InputStream in =socket.getInputStream();
        //创建一个byte数组，对于数据进行存储
        ByteArrayOutputStream by = new ByteArrayOutputStream();

        int len ;
        byte[] buffer = new byte[5];
        while ((len = in.read(buffer)) != -1){
            by.write(buffer,0,len);
        }

        System.out.println(by);

        //4.关闭流
        socket.close();
        in.close();


    }
}
